package com.bms.cfcmms.util.jwt;

import java.util.Date;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;


import io.jsonwebtoken.*;

/**
 * 用于生成或解密每次请求的jwt token
 *
 * Created by Administrator on 2016/11/28.
 */
public class JwtUtil {

    /***
     * 生成Token码
     * @param id
     * @param subject : 用户信息的json字符串
     * @param ttlMillis : 指token有效时间
     * @return
     * @throws Exception
     *//*
    public String createJwt(String id, String subject, long ttlMillis)throws Exception{
        //The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

    //We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret());
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder().setId(id)
                .setIssuedAt(now)
                .setSubject(subject)
                .setIssuer(issuer).signWith(signatureAlgorithm, signingKey);

    //if it has been specified, let's add the expiration
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

    //Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }*/

    /***
     * 解码和验证token
     * @param jwt : 前段传来的token码
     *//*
    private Claims parseJWT(String jwt) {
        //This line will throw an exception if it is not a signed JWS (as expected)
        Claims claims = Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(apiKey.getSecret()))
                .parseClaimsJws(jwt).getBody();
        System.out.println("ID: " + claims.getId());
        System.out.println("Subject: " + claims.getSubject());
        System.out.println("Issuer: " + claims.getIssuer());
        System.out.println("Expiration: " + claims.getExpiration());
        return claims;
    }*/
    private String profiles;

    /**
     * 由字符串生成加密key
     * @return
     */
    public SecretKey generalKey(){
        String stringKey = profiles + "7786df7fc3a34e26a61c034d5ec8245d";
        byte[] encodedKey = Base64.decodeBase64(stringKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 创建 jwt
     * @param id
     * subject  : 用户信息
     * @param ttlMillis : token过期时间
     * @return 加密后的code
     * @throws Exception
     */
    public String createJWT(String id, String loginName,String password, long ttlMillis){

        String subject = "name:{'"+loginName+"'},password:{'"+password+"'}";//组装一下成为json类型

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System. currentTimeMillis();
        Date now = new Date( nowMillis);
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts. builder()
                .setId(id)
                .setIssuedAt(now)
                .setSubject(subject)
                .signWith(signatureAlgorithm, key);
        if (ttlMillis >= 0){
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date( expMillis);
            builder.setExpiration( exp);
        }
        return builder.compact();
    }

    /**
     * 解密 jwt,
     * @param jwt
     * @return 解密后的内容,可用claims.get方法提取出数据
     * @throws Exception
     *
     */
    public Claims parseJWT(String jwt){
        SecretKey key = generalKey();
        Claims claims = Jwts. parser()
                .setSigningKey( key)
                .parseClaimsJws( jwt).getBody();
        return claims;
    }
}
